package simple;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
public class SimpleServer {
    public static void main(String[] args) {
        // 定义端口号
        if (args == null || args.length == 0){
            throw new IllegalArgumentException("plz provide port param");
        }
        int port = Integer.parseInt(args[0]);

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器启动，监听端口：" + port);
            
            // 无限循环等待客户端连接
            while (true) {
                try {
                    // 接受客户端连接
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("接收到新的客户端连接");
                    
                    // 处理客户端请求（例如读取和回应）
                    handleClient(clientSocket);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void handleClient(Socket clientSocket) throws Exception {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
            
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println("收到客户端消息：" + inputLine);
                // 回送相同的消息给客户端
                out.println("Echo: " + inputLine);
            }
        } finally {
            clientSocket.close(); // 关闭连接
        }
    }
}